package edu.gatech.gro.model.parser;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
import edu.gatech.gro.model.User;

public class UserJsonHandler extends JsonHandler {

	private static final String TAG = "USER_JSON_HANDLER";

	@Override
	protected void parseDataArray() {
		List<User> dataParsed = new ArrayList<User>();
		try {
			JSONArray array = json.getJSONArray("data");
			for (int i = 0; i < array.length(); i++) {
				dataParsed.add(getUser(array.getJSONObject(i)));
			}
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}
		getResponse().setData(dataParsed);
	}

	@Override
	protected void parseData() {
		User dataParsed = null;
		try {
			dataParsed = getUser(json.getJSONObject("data"));
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}
		getResponse().setData(dataParsed);
	}

	public User getUser(JSONObject obj) {
		User u = new User();
		try {
			parseAbstractObject(u, obj);
			u.setUsername(obj.getString("username"));
			u.setUsernameClean(obj.getString("usernameClean"));
			if (obj.has("email")) {
				u.setEmail(obj.getString("email"));
			}
			if (obj.has("password")) {
				u.setPassword(obj.getString("password"));
			}
			if (obj.has("lists")) {
				u.setLists(NamedListJsonHandler.getNamedLists(obj.getJSONArray("lists")));
			}
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}
		return u;
	}
}
